<html>
<head>
	<link REL="SHORTCUT ICON" HREF="http://www.example.org/myicon.ico" type="image/x-icon"/>
   <link REL="SHORTCUT" HREF="http://www.example.org/myicon.ico" type="image/x-icon"/>
   <title>Homework</title>
</head>
<body>
    <a href="http://localhost:8080/addNewFile">Add new file to database.</a></br></br>
    <p>Type here to find the word:</p>
	<p><input id="userInput" type="text" name="find" onkeyup="get(this)"></p>
	<span name="Output" id="Output"></span>
	<script language="JavaScript" type="text/javascript">
		var http_request = false;
		
		function makePOSTRequest(url, parameters) {
		  http_request = false;
		  if (window.XMLHttpRequest) { // Mozilla, Safari,...
		    http_request = new XMLHttpRequest();
		    if (http_request.overrideMimeType) {
		      http_request.overrideMimeType('text/html');
		    }
		  } else if (window.ActiveXObject) { // IE
		    try {
		      http_request = new ActiveXObject("Msxml2.XMLHTTP");
		    } catch (e) {
		      try {
		        http_request = new ActiveXObject("Microsoft.XMLHTTP");
		      } catch (e) {}
		    }
		  }
		  if (!http_request) {
		    document.getElementById('Output').innerHTML = "Cannot create XMLHTTP instance";
		    return false;
		  }
		  http_request.onreadystatechange = function() {
            alertContents(http_request); 
        };
		  http_request.open('GET', url, true);
		  http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		  http_request.setRequestHeader("Content-length", parameters.length);
		  http_request.setRequestHeader("Connection", "close");
		  http_request.send(parameters);
		}
		
		function commandToHtml(jsonStr) {
			var obj = eval( "(" + jsonStr + ")" );
			if (obj.type == 13) {
				var result = "Error"
				return result;
			} else if (obj.type == 9) {
				var result = "result: ";
				for (var i = 0; i < obj.body.length; ++i) {
				   result += "<a href=\"http://localhost:8080/keyWords=";
					result += obj.body[i].key;				
					result += "\">";
					result += obj.body[i].key;
					result += "</a>&nbsp";
                                        result += "(" + obj.body[i].popularity + ");&nbsp&nbsp&nbsp&nbsp&nbsp ";
				}
				return result;
			} else {
				return jsonStr;
			}
		}
		
		function alertContents(httpRequest) {
		  if (httpRequest.readyState == 4) {
		    if (http_request.status == 200) {
		      result = httpRequest.responseText;
		      
		      document.getElementById('Output').innerHTML = commandToHtml(result);
		    } else {
		      document.getElementById('Output').innerHTML = "There was a problem with the request.";
		    }
		  }
		}

		function get(obj) {
		  var poststr = "userInput=" + encodeURI( document.getElementById("userInput").value );
		  makePOSTRequest('http://localhost:8080/' + poststr, poststr);
		}
		
	</script>
</body>
</html>
